package com.fsd.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.fsd.admin.model.Z_project;
import com.fsd.admin.service.*;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Z_projectbill;
import com.fsd.admin.dao.Z_projectbillDao;

@Repository("z_projectbillServiceImpl")
public class Z_projectbillServiceImpl extends BaseServiceImpl<Z_projectbill, String> implements Z_projectbillService{
    
    private static final Logger log = Logger.getLogger(Z_projectbillServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "z_projectbillDaoImpl")
	public void setBaseDao(Z_projectbillDao Z_projectbillDao) {
		super.setBaseDao(Z_projectbillDao);
	}
	
	@Resource(name = "z_projectbillDaoImpl")
	private Z_projectbillDao objectDao;

    @Autowired
    private Z_projectService projectService;

	@Autowired
	private A_EmployeeService employeeService;

	@Autowired
	private Sys_SystemParametersService systemParametersService;

	@Autowired
	private E_pushtemplatesService pushtemplatesService;

	@Autowired
	private Z_emailService emailService;
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		if(objectMap.get("projectid") == null && "".equals(objectMap.get("projectid"))){
			throw new BusinessException(depict + "缺少项目编码");
		}else{
			c.add(Restrictions.eq("f_projectid", objectMap.get("projectid")));
		}
		return objectDao.findPager(param , c);
	}

	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getObjectPageList1(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
			c.add(Restrictions.like("f_projectname", "%" + objectMap.get("name") + "%"));
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
    @Override
	public void save(Z_projectbill obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            Z_projectbill old_obj = objectDao.get(obj.getId());
			old_obj.setF_name(obj.getF_name());
			old_obj.setF_money(obj.getF_money());
			old_obj.setF_detail(obj.getF_detail());
			old_obj.setF_url(obj.getF_url());
            old_obj.setF_lastupdatedate(this.getData());//设置修改日期
			old_obj.setF_updateemployeeid(employee.getId());//设置修改用户id
			old_obj.setF_updateemployeename(employee.getRealname());//设置修改用户姓名
            objectDao.update(old_obj);
        }else{
            //添加
			Z_project project = projectService.get(obj.getF_projectid());
			String level = obj.getF_level();
			if(level.equals("xj")){
				if(project.getF_isschool() == null || !project.getF_isschool().equals("true")){
					throw new BusinessException("该项目没有被评为校级项目，无法进行校级报账");
				}else{
					String sql = "select * from Z_projectbill where f_projectid = ? and f_level = ?";
					List<Z_projectbill> list = objectDao.queryBySql1(sql, project, "xj");
					double allMoney = 0;
					for (Z_projectbill z_projectbill : list) {
						allMoney = allMoney + Double.valueOf(z_projectbill.getF_money());
					}
					if(allMoney > Double.valueOf(project.getF_schoolmoney())){
						throw new BusinessException("该项目报账总金额已超过项目资助金额，无法进行报账");
					}
				}
			}else if(level.equals("sj")){
				if(project.getF_isprovince() == null || !project.getF_isprovince().equals("true")){
					throw new BusinessException("该项目没有被评为省级项目，无法进行省级报账");
				}else{
					String sql = "select * from Z_projectbill where f_projectid = ? and f_level = ?";
					List<Z_projectbill> list = objectDao.queryBySql1(sql, project, "sj");
					double allMoney = 0;
					for (Z_projectbill z_projectbill : list) {
						allMoney = allMoney + Double.valueOf(z_projectbill.getF_money());
					}
					if(allMoney > Double.valueOf(project.getF_provincemoney())){
						throw new BusinessException("该项目报账总金额已超过项目资助金额，无法进行报账");
					}
				}
			}else if(level.equals("gjj")){
				if(project.getF_iscountry() == null || !project.getF_iscountry().equals("true")){
					throw new BusinessException("该项目没有被评为国家级项目，无法进行国家级报账");
				}else{
					String sql = "select * from Z_projectbill where f_projectid = ? and f_level = ?";
					List<Z_projectbill> list = objectDao.queryBySql1(sql, project, "gjj");
					double allMoney = 0;
					for (Z_projectbill z_projectbill : list) {
						allMoney = allMoney + Double.valueOf(z_projectbill.getF_money());
					}
					if(allMoney > Double.valueOf(project.getF_countrymoney())){
						throw new BusinessException("该项目报账总金额已超过项目资助金额，无法进行报账");
					}
				}
			}

			obj.setF_projectname(project.getF_name());
            obj.setId(this.getUUID());//设置主键
			obj.setF_adddate(this.getData());//设置添加日期
			obj.setF_addemployeeid(employee.getId());//设置添加用户id
			obj.setF_addemployeename(employee.getRealname());//设置添加用户姓名
			obj.setF_deleted("0");//设置删除标志(0:正常 1：已删除)
			obj.setF_state("0");//0代表待审核
			objectDao.save(obj);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			String pushUsers = systemParametersService.getParameterValueByCodeSql("FSDBILLPUSH");
			if(pushUsers != null && !"".equals(pushUsers)){
				if(pushUsers.length() > 32){
					String[] dir = pushUsers.split(",");
					for (String userid : dir) {
						A_Employee pushUser = employeeService.get(userid);
						// 发送微信通知
						if(employee.getIswechatbind() != null && "true".equals(employee.getIswechatbind())){
							String wechatApiId = systemParametersService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
							TemplateMessage message = new TemplateMessage();
							message.setItem("first", "尊敬的" + employee.getRealname() + "，您有新的任务，请及时处理", "#000000");
							message.setItem("keyword1", "项目报账", "#000000");
							message.setItem("keyword2", formatter.format(obj.getF_adddate()), "#000000");
							message.setItem("remark", "兰州工业学院创新创业学院", "#1111EE");
							pushtemplatesService.sendTemplateMessage(wechatApiId, "lcdbtx", employee, message);
						}
						// 发送站内信通知
						StringBuffer sb = new StringBuffer();
						sb.append("任务名称：项目报账");
						sb.append("<br />");
						sb.append("提交时间：" + formatter.format(obj.getF_adddate()));
						sb.append("<br />");
						sb.append("兰州工业学院创新创业学院");
						emailService.saveMessage("您有新的任务，请及时处理。", sb.toString(), employee);
					}
				}else{
					A_Employee pushUser = employeeService.get(pushUsers);
					// 发送微信通知
					if(employee.getIswechatbind() != null && "true".equals(employee.getIswechatbind())){
						String wechatApiId = systemParametersService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
						TemplateMessage message = new TemplateMessage();
						message.setItem("first", "尊敬的" + employee.getRealname() + "，您有新的任务，请及时处理", "#000000");
						message.setItem("keyword1", "项目报账", "#000000");
						message.setItem("keyword2", formatter.format(obj.getF_adddate()), "#000000");
						message.setItem("remark", "兰州工业学院创新创业学院", "#1111EE");
						pushtemplatesService.sendTemplateMessage(wechatApiId, "lcdbtx", employee, message);
					}
					// 发送站内信通知
					StringBuffer sb = new StringBuffer();
					sb.append("任务名称：项目报账");
					sb.append("<br />");
					sb.append("提交时间：" + formatter.format(obj.getF_adddate()));
					sb.append("<br />");
					sb.append("兰州工业学院创新创业学院");
					emailService.saveMessage("您有新的任务，请及时处理。", sb.toString(), employee);
				}
			}
        }
    }

    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
    @Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			this.delete(id);
		}
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
    @Override
	public Z_projectbill getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_projectbill obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}

	/**
	 * 更新审批状态
	 * @param parameters
	 * @throws Exception
	 */
	public void updateEnabledObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		if(isEnabled){
			for (String id : idList) {
				Z_projectbill projectbill = this.get(id);
				projectbill.setF_state("1");
				this.update(projectbill);

				A_Employee employee = employeeService.get(projectbill.getF_addemployeeid());
				String text = systemParametersService.getParameterValueByCodeSql("FSDBILLSUBMITTIME");

				// 发送微信通知
				if(employee.getIswechatbind() != null && "true".equals(employee.getIswechatbind())){
					String wechatApiId = systemParametersService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
					TemplateMessage message = new TemplateMessage();
					message.setItem("first",  "恭喜，您的项目报账已审核通过", "#000000");
					message.setItem("keyword1", employee.getRealname(), "#000000");
					message.setItem("keyword2", "项目报账", "#000000");
					message.setItem("keyword3", "允许报账", "#000000");
					message.setItem("remark", "您的报账信息已通过审核，"+ text +"", "#1111EE");
					pushtemplatesService.sendTemplateMessage(wechatApiId, "lcsptx", employee, message);
				}
				// 发送站内信通知
				StringBuffer sb = new StringBuffer();
				sb.append("申请人：" + employee.getRealname());
				sb.append("<br />");
				sb.append("审批类型：" + "");
				sb.append("<br />");
				sb.append("审批状态：允许报账");
				sb.append("<br />");
				sb.append("您的报账信息已通过审核，"+ text +"");
				emailService.saveMessage("恭喜，您的项目报账已审核通过。", sb.toString(), employee);
			}
		}else{
			for (String id : idList) {
				Z_projectbill projectbill = this.get(id);
				projectbill.setF_state("0");
				this.update(projectbill);
				A_Employee employee = employeeService.get(projectbill.getF_addemployeeid());
				// 发送微信通知
				if(employee.getIswechatbind() != null && "true".equals(employee.getIswechatbind())){
					String wechatApiId = systemParametersService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
					TemplateMessage message = new TemplateMessage();
					message.setItem("first",  "抱歉，您的项目报账审核未通过。", "#000000");
					message.setItem("keyword1", employee.getRealname(), "#000000");
					message.setItem("keyword2", "项目报账", "#000000");
					message.setItem("keyword3", "拒绝报账", "#000000");
					message.setItem("remark", "您的项目报账审核未通过。", "#C75450");
					pushtemplatesService.sendTemplateMessage(wechatApiId, "lcsptx", employee, message);
				}
				// 发送站内信通知
				StringBuffer sb = new StringBuffer();
				sb.append("申请人：" + employee.getRealname());
				sb.append("<br />");
				sb.append("审批类型：" + "");
				sb.append("<br />");
				sb.append("审批状态：拒绝报账");
				sb.append("<br />");
				sb.append("您的项目报账审核未通过。");
				emailService.saveMessage("抱歉，您的项目报账审核未通过。", sb.toString(), employee);
			}
		}
    }

	/**
	 * 根据项目ID加载项目报账信息
	 * @param projectId
	 * @return
	 * @throws Exception
	 */
    public List<Z_projectbill> getListByProjectId(String projectId) throws Exception{
		String sql = "select * from Z_projectbill where f_projectid = ? and f_deleted = ? and f_state = ?";
		return objectDao.queryBySql1(sql, projectId, "0", "1");
	}

	/**
	 * 根据项目ID和报账级别加载项目报账信息
	 * @param projectId
	 * @param level
	 * @return
	 * @throws Exception
	 */
	public List<Z_projectbill> getListByProjectIdAndLevel(String projectId, String level) throws Exception{
		String sql = "select * from Z_projectbill where f_projectid = ? and f_level = ? and f_deleted = ? and f_state = ?";
		return objectDao.queryBySql1(sql, projectId, level, "0", "1");
	}
}
